/**
 * $Revision: 1.0 $
 * $Author: Eric Yang $
 * $Date: Aug 7, 2009 10:38:54 PM $
 *
 * Author: Eric Yang
 * Date  : Aug 7, 2009 10:38:54 PM
 *
 */
package com.gooex.service.organization.impl;

import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.c4j.string.StringTools;
import org.c4j.system.web.hibernate.BaseHibernateService;

import com.gooex.domain.organization.Area;
import com.gooex.service.organization.AuthorityContext;
import com.gooex.service.organization.IAreaManager;
import com.gooex.service.organization.exception.AreaException;

/**
 * @author Eric Yang
 * @version 1.0
 */
public class AreaManagerImpl extends BaseHibernateService implements IAreaManager {

	private static final Log logger = LogFactory.getLog(AreaManagerImpl.class);

	public Area getArea(String id) {
		if (StringTools.isBlankOrNull(id))
			return null;
		return (Area) getHibernateTemplate().get(Area.class, id);
	}

	public List<Area> getAreas() {
		return getHibernateTemplate().find("from Area");
	}

	public Area getAreaByName(String name) {
		String hql = "from " + Area.class.getName() + " where name=?";
		List<Area> areas = getHibernateTemplate().find(hql, name);
		if (areas != null && areas.size() == 1)
			return areas.get(0);
		logger.debug("no area whoes name like \"" + name + "\"");
		return null;
	}

	public void saveArea(Area area) {
		if (StringTools.isBlankOrNull(area.getId())) {
			area.setId(null);
		}
		getHibernateTemplate().saveOrUpdate(area);
	}

	public void removeArea(Area area) throws AreaException {
		area = getArea(area.getId());
		if (AuthorityContext.getSuperArea().equals(area)) {
			logger.debug("Area[" + area.getName() + "] is super area, can't be removed!");
			throw new AreaException("Can't remove super area!");
		}
		getHibernateTemplate().delete(area);
	}
}
